package cc.mcyx.ychat.service.impl

import cc.mcyx.ychat.execution.MessageException
import cc.mcyx.ychat.mapper.UserFansMapper
import cc.mcyx.ychat.model.UserFans
import cc.mcyx.ychat.service.UserService
import cc.mcyx.ychat.vo.request.page.SearchPage
import cn.hutool.core.util.ObjectUtil
import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.spring.service.impl.ServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class UserFansService : ServiceImpl<UserFansMapper, UserFans>() {


    @Autowired
    lateinit var userService: UserService

    fun follow(followUid: Int): Boolean {
        val followUser = userService.getById(followUid)
        if (ObjectUtil.isNull(followUser)) throw MessageException("对方用户不存在", 400)
        val user = userService.getCurrentUser()
        val where = QueryWrapper.create().eq(UserFans::userId, user.id).eq(UserFans::fansId, followUser.id)
        val followInfo = getOne(where) ?: UserFans(null, user.id, followUser.id)
        followInfo.also { it.follow = !it.follow }
        saveOrUpdate(followInfo)
        return followInfo.follow
    }

    fun getFollow(searchPage: SearchPage): Page<UserFans> {
        return page(Page<UserFans>().also {
            it.pageNumber = searchPage.page
            it.pageSize = searchPage.limit
        })
    }
}